package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.Grade;
import com.xmy.cultivate.entity.LklMerchantSet;
import com.xmy.cultivate.entity.Merchant;
import com.xmy.cultivate.entity.StudentGrade;
import com.xmy.cultivate.mapper.LklMerchantSetMapper;
import com.xmy.cultivate.service.IGradeService;
import com.xmy.cultivate.service.ILklMerchantSetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.service.IStudentGradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 拉卡拉商户设置 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2025-03-22
 */
@Service
public class LklMerchantSetServiceImpl extends ServiceImpl<LklMerchantSetMapper, LklMerchantSet> implements ILklMerchantSetService {
    @Autowired
    LklMerchantSetMapper lklMerchantSetMapper;

    @Autowired
    IStudentGradeService iStudentGradeService;

    @Autowired
    IGradeService iGradeService;

    @Override
    public List<Merchant> getSchool() {
        return lklMerchantSetMapper.getSchool();
    }

    @Override
    public List<Merchant> getMerchantSchool() {
        return lklMerchantSetMapper.getMerchantSchool();
    }

    @Override
    public List<LklMerchantSet> getMerchant(Long schoolId) {
        return lklMerchantSetMapper.getMerchant(schoolId);
    }

    @Override
    public String getMerchantName(String yearPart, String quarterNum, Long subjectsId, Long studentId) {
        return lklMerchantSetMapper.getMerchantName(yearPart,quarterNum,subjectsId,studentId);
    }



    @Override
    public LklMerchantSet getMerchantNo(String yearPart, String quarterNum, Long subjectsId, Long studentId,Long schoolId){
        LklMerchantSet lklMerchantSet = null;
        //切换后的商户号
        lklMerchantSet = lklMerchantSetMapper.afterSwitchMerchantNo(yearPart, quarterNum, subjectsId, studentId, schoolId);
        if (!Objects.isNull(lklMerchantSet)){
            return lklMerchantSet;
        }

        StudentGrade studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(schoolId,studentId,subjectsId,Integer.parseInt(yearPart),Integer.parseInt(quarterNum),1);
        if (!Objects.isNull(studentGrade)){
            Grade grade = iGradeService.getById(studentGrade.getGradeId());
            if (!Objects.isNull(grade)){
                //切换前的商户号
                lklMerchantSet = lklMerchantSetMapper.beforeSwitchMerchantNo(yearPart,quarterNum,grade.getTeacherId(), schoolId);
            }
        }


        if (!Objects.isNull(lklMerchantSet)){
           return lklMerchantSet;
        }

        //通过校区获取商户号
        lklMerchantSet = lklMerchantSetMapper.getMerchantNoBySchoolId(yearPart ,quarterNum,schoolId);
        return lklMerchantSet;
    }

}
